import * as React from 'react';
import { lazy } from 'react';
import { ItemType } from 'antd/es/menu/hooks/useItems';
import { BreadcrumbItemType, BreadcrumbSeparatorType } from 'antd/es/breadcrumb/Breadcrumb';
import { Navigate } from 'react-router-dom';
import { WitRouterProp } from '@/router/types';
import { WitIcon } from '@/components/Icon';
import { store } from '@/store';
import { getToken, removeToken } from '@/utils/storage';
import { setLogin } from '@/store/reducer/theme/action';
import { useWitTheme } from '@/hook';

// 懒加载
export const lazyLoad = (moduleName: string) => {
  const Module = lazy(() => import(`@/views/${moduleName}/index.tsx`));
  return <Module />;
};
// 全局路由守卫
export const RouterBeforeEach = ({ children }: any) => {
  const theme = useWitTheme();
  const { login } = theme;
  const token = getToken();
  if (!login || !token) {
    if (login) store.dispatch(setLogin(false));
    removeToken();
    return <Navigate to="/login" replace />;
  }
  return children;
};

// 根据路由获取菜单
export const getRouteMenu = (menus: any[]): ItemType[] & Partial<BreadcrumbItemType & BreadcrumbSeparatorType>[] =>
  menus.map(({ icon, children, name, component, disable, path, ...item }) => ({
    ...item,
    path,
    key: path,
    label: name,
    title: name,
    icon: <WitIcon key={path} type={icon} />,
    children: children && getRouteMenu(children),
  }));

// 获取路由，可用useRouters构子
export const getRouters = (item: any[]): Array<WitRouterProp> =>
  item.map(({ path, name, component, children, ...r }) => ({
    ...r,
    path,
    element: lazyLoad(component),
    children: children && getRouters(children),
  }));

/**
 * 以递归的方式展平react router数组 面包宵路由数据
 */
export const flattenRoutes = (arr: any[]): any =>
  arr.reduce((prev, item) => {
    const { path, name, icon } = item;
    if (item.component && item.component !== 'Layout') {
      prev.push({
        path,
        title: (
          <>
            <WitIcon key={path} type={icon} />
            <span>{name !== '首页' ? name : ''}</span>
          </>
        ),
      });
    }
    return prev.concat(Array.isArray(item.children) ? flattenRoutes(item.children) : []);
  }, []);
